#include "System.h"
#include "Ui/Manager.h"

System::System() {
    Initialize();
    program.SetFramerateLimit(60);
}

System::~System() {
    program.Close();
}

/**
 * System::Initialize
 * Initialize the program and library to get it ready to start the program.
 */
void System::Initialize() {
    screenWidth = 800;
    screenHeight = 600;
    bpp = 32;
    state = MENU;

    //initialize the gui system
    PickinOpenSticks::Ui::Manager::GetSingleton().Initialize(&program);

    program.Create(VideoMode(screenWidth, screenHeight, bpp), "Pickin' Open Sticks");
}

/**
 * System::SetState
 * Sets the "state" variable in the Program class.  Can be RUNNING, PAUSED, or EXIT.
 * @param val ProgramState     The new program state
 */
void System::SetState(ProgramState val) {
    state = val;
}

/**
 * System::GetState()
 * Returns the current state of the program.  Can be RUNNING, PAUSED, or EXIT.
 * @return Returns the program's state
 */
ProgramState System::GetState() {
    return state;
}

/**
 * System::BeginDraw
 * Wrapper to get the RenderWindow ready to draw stuff
 */
void System::BeginDraw() {
    program.Clear(Color(25, 125, 25));
}

/**
 * System::EndDraw
 * Wrapper to display contents to the screen
 */
void System::EndDraw() {
    program.Display();
}

/**
 * System::Draw
 * Wrapper to draw a sprite to the buffer
 * @param sprite Sprite      The Sprite object to draw
 */
void System::Draw(Sprite &sprite) {
    program.Draw(sprite);
}

/**
 * System::CheckEvents()
 * Wrapper for RenderWindow's GetEvent function
 */
void System::CheckEvents() {
    while (program.GetEvent(event)) {

        if (event.Type == Event::Closed)
            state = EXIT;
        else {
            if (event.Type == Event::KeyPressed)
                if (event.Key.Code == Key::Escape)
                    (this->state == MENU) ? state = EXIT : state = MENU;
            PickinOpenSticks::Ui::Manager::GetSingleton().RegisterEvent(&event);

        }
    }
}

void System::HandleKeyboardInput(Character& player) {
    // Handle input - Player controls
    if (Key(Key::Left) || Key(Key::A)) {
        player.Move(LEFT);
    } else if (Key(Key::Right) || Key(Key::D)) {
        player.Move(RIGHT);
    }
    if (Key(Key::Up) || Key(Key::W)) {
        player.Move(UP);
    } else if (Key(Key::Down) || Key(Key::S)) {
        player.Move(DOWN);
    }
    if (Key(Key::F)) {
        player.SetSpeed(10);
    }

    // Handle input - Program controls
    if (Key(Key::F4)) {
        SetState(EXIT);
    }
}

/**
 * System::Key
 * Returns whether or not this key is being hit
 * @return code KeyCode
 */
bool System::Key(Key::Code code) {
    return program.GetInput().IsKeyDown(code);
}

/**
 * System::GetFramesPerSecond
 * Returns the frames per second
 * @return string The Frame Rate in a string format
 */
string System::GetFramesPerSecond() {
    char fps[12];
    int fpsLength = sprintf(fps, "%.2f", 1.0f / program.GetFrameTime());
    return string(fps, fpsLength);
}


